package com.xbongbong.paas.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.manager.DepartmentManager;
import com.xbongbong.paas.manager.feign.OrganizationFeignClient;
import com.xbongbong.paas.pojo.dto.DepartmentRefreshDTO;
import com.xbongbong.paas.pojo.dto.DepartmentRefreshStatusDTO;
import com.xbongbong.paas.pojo.dto.DepartmentRefreshTimesDTO;
import com.xbongbong.paas.pojo.vo.DepartmentRefreshStatusVO;
import com.xbongbong.paas.pojo.vo.DepartmentRefreshTimesVO;
import com.xbongbong.paas.pojo.vo.DepartmentRefreshVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.user.pojo.dto.SyncOrganizationDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * @author kaka
 * @time 2018-9-5 18:46
 */
@Service("departmentManager")
public class DepartmentManagerImpl implements DepartmentManager {

    private static final Logger LOG = LoggerFactory.getLogger(DepartmentManagerImpl.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private OrganizationFeignClient organizationFeignClient;

    @Override
    public DepartmentRefreshVO refresh(DepartmentRefreshDTO refreshDTO) throws XbbException {
        DepartmentRefreshVO refreshVO = new DepartmentRefreshVO();
        String corpid = refreshDTO.getCorpid();
        String userId = refreshDTO.getUserId();

        // 获取每天最多同步组织架构次数
        Integer useTimes = StringUtil.toInt(paasRedisHelper.getValue(RedisPrefixConstant.DEPARTMENT_REFRESH_TIMES, corpid), PaasConstant.MAX_DEPARTMENT_REFRESH_TIMES_PER_DAY);
        if (useTimes <= 0) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.DEPARTMENT_REFRESH_TIMES_EXCEED);
        }

        SyncOrganizationDTO syncOrganizationDTO = new SyncOrganizationDTO();
        syncOrganizationDTO.setUpdateCorpid(corpid);

        try {
            Locale locale = LocaleContextHolder.getLocale();
            String lang = locale.toString();
            XbbResponse<BaseVO> baseRt = organizationFeignClient.syncDepartmentUser(syncOrganizationDTO, lang);
            if (baseRt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            if (baseRt.getCode() != null && baseRt.getCode().equals(ErrorCodeEnum.API_SUCCESS.getCode())) {
                useTimes--;
                // 更新redis
                paasRedisHelper.setValue(RedisPrefixConstant.DEPARTMENT_REFRESH_TIMES, corpid, useTimes, RedisTimeConstant.LONG_DURATION);
                refreshVO.setUseTimes(useTimes);
            } else {
                throw new XbbException(baseRt.getCode(), baseRt.getMsg());
            }

        } catch (XbbException xe) {
          throw xe;
        } catch (Exception e) {
            LOG.error("DepartmentManagerImpl.refresh 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        return refreshVO;
    }

    @Override
    public DepartmentRefreshTimesVO getFreshTimes(DepartmentRefreshTimesDTO refreshTimesDTO) throws XbbException {
        DepartmentRefreshTimesVO refreshTimesVO = new DepartmentRefreshTimesVO();
        String corpid = refreshTimesDTO.getCorpid();

        try {
            Integer useTimes = StringUtil.toInt(paasRedisHelper.getValue(RedisPrefixConstant.DEPARTMENT_REFRESH_TIMES, corpid), PaasConstant.MAX_DEPARTMENT_REFRESH_TIMES_PER_DAY);
            if(useTimes < 0) {
                useTimes = 0;
            }
            refreshTimesVO.setUseTimes(useTimes);
        } catch (Exception e) {
            LOG.error("DepartmentManagerImpl.getFreshTimes 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return refreshTimesVO;
    }

    @Override
    public DepartmentRefreshStatusVO getFreshStatus(DepartmentRefreshStatusDTO refreshStatusDTO) throws XbbException {
        DepartmentRefreshStatusVO refreshStatusVO = new DepartmentRefreshStatusVO();
        String corpid = refreshStatusDTO.getCorpid();
        try {
            /*
             * {"code":1,"msg":"xxxx"} 0.未开始同步，1.成功，2，正在同步中 >2 错误信息
             */
            String refreshStatus = paasRedisHelper.getValue(RedisPrefixConstant.DEPARTMENT_REFRESH_STATUS, corpid);
            if(refreshStatus != null) {
                try {
                    JSONObject refreshStatusJson = JSONObject.parseObject(refreshStatus);
                    if(refreshStatusJson != null) {
                        Integer syncCode = refreshStatusJson.getInteger("code");
                        String msg = refreshStatusJson.getString("msg");
                        if(syncCode != null && !StringUtil.isEmpty(msg)) {
                            refreshStatusVO.setSyncCode(syncCode);
                            refreshStatusVO.setMsg(msg);
                        }
                    } else {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                } catch (Exception e) {
                    LOG.error("syncDepUserStatusBefore转化为json时出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), MessageConstant.DEPARTMENT_REFRESH_FAIL);
                }
            } else {
                refreshStatusVO.setSyncCode(0);
                refreshStatusVO.setMsg(I18nMessageUtil.getMessage(I18nStringConstant.SYNC_NOT_START));
            }
        } catch (XbbException xe) {
           throw xe;
        } catch (Exception e) {
            LOG.error("DepartmentManagerImpl.getFreshTimes 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return refreshStatusVO;
    }
}
